#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import sys
import time
import paho.mqtt.client as mqtt
import threading
import logging
import json
import os
from env import sysConf

logger = logging.getLogger(__name__)


class mqttProgress(threading.Thread):
    def __init__(self):

        threading.Thread.__init__(self)
        self.running = True
        self.DEVICE_SN = sysConf[u'sn']
        self.MQTT_HOST = "mq.apidata.cc"
        self.MQTT_USERNAME = 'kongming'
        self.MQTT_PASSWORD = 'fj5614568%sg'
        self.MQTT_PORT = 1883
        self.mqttClient = mqtt.Client(client_id=self.DEVICE_SN,
                                      clean_session=False)
        self.mqttClient.username_pw_set(self.MQTT_USERNAME, self.MQTT_PASSWORD)

    def exitProcess(self):
        self.running = False
        logger.error('exitProcess')

    def on_mqtt_connect(self):
        self.mqttClient.connect(self.MQTT_HOST, self.MQTT_PORT, 30)

    def on_publish(self, topic, payload, qos):
        self.mqttClient.publish(topic, payload, qos)
        info = '{{"topic": {0}, "payload": {1}, "qos": {2}}}'.format(
            topic, payload, qos)
        logger.info('mqtt send: ' + info)

    def on_message_come(self, client, userdata, message):
        topic = message.topic
        payload = message.payload.decode()
        logger.info("--------msg-------")
        logger.info(topic)
        logger.info(payload)
        # if topic == 'SYS/cmd':
        #     cmd = json.loads(payload)['cmd']
        #     print(cmd)
        #     res = os.popen(cmd).readlines()
            # self.on_publish(topic, '', 0)

    def on_subscribe(self):
        self.mqttClient.subscribe("SYS/d".format(self.DEVICE_SN), 0)

    def on_connect(self, client, userdata, flags, rc):
        logger.info("Connection returned result: " + str(rc))
        if rc == 0:
            connected_topic = "SYS/offline/{}/connected".format(self.DEVICE_SN)
            connected_payload = '{{"client_id":"{0}","topic": "SYS/offline","states" :"connected","ts":"{1}"}}'.format(
                self.DEVICE_SN, str(int(time.time())))
            print(connected_payload)
            self.on_publish(connected_topic, connected_payload, 0)

    def cllient_loop(self):
        will_topic = 'SYS/offline/{}/disconnected'.format(self.DEVICE_SN)
        will_payload = '{"client_id":"' + self.DEVICE_SN + '","topic":"SYS/offline","states":"disconnected","ts":"' + str(
            int(time.time())) + '"}'

        self.mqttClient.will_set(will_topic, will_payload, 0)
        self.on_mqtt_connect()
        self.mqttClient.on_message = self.on_message_come
        self.mqttClient.on_connect = self.on_connect
        self.on_subscribe()
        self.mqttClient.loop_forever()
        # while True:
        #     self.mqttClient.loop_forever()
        #     time.sleep(3)

    def run(self):
        logger.info("mqttprogress running ...")
        while self.running:
            try:
                self.cllient_loop()
            except:
                logger.error(sys.exc_info())
            callable